package com.copd.controller;

import com.copd.common.Result;
import com.copd.dto.RoleDTO;
import com.copd.entity.Role;
import com.copd.entity.User;
import com.copd.mapper.UserMapper;
import com.copd.service.RoleService;
import com.copd.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "角色管理")
@RestController
@RequestMapping("/api/roles")
public class RoleController {
    
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @ApiOperation("获取所有角色")
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<Role>> getAllRoles() {
        return Result.success("获取角色列表成功", roleService.getAllRoles());
    }
    
    @ApiOperation("获取用户的角色")
    @GetMapping("/user/{userId}")
    public Result<List<Role>> getRolesByUserId(
            @ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Integer userId,
            HttpServletRequest request) {
        try {
            // 验证权限：用户只能查看自己的角色，管理员可以查看所有用户的角色
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                Integer currentUserId = jwtUtil.getUserIdFromToken(token);
                
                if (currentUserId.equals(userId) || hasAdminRole(currentUserId)) {
                    List<Role> roles = roleService.getRolesByUserId(userId);
                    return Result.success("获取用户角色成功", roles);
                } else {
                    logger.warn("权限不足: 用户{}试图查询用户{}的角色", currentUserId, userId);
                    return Result.error("403", "无权查看其他用户的角色");
                }
            }
            return Result.error("401", "未登录或登录已过期");
        } catch (Exception e) {
            logger.error("获取用户角色失败", e);
            return Result.error("500", "获取用户角色失败");
        }
    }
    
    @ApiOperation("根据ID获取角色")
    @GetMapping("/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Role> getRoleById(@PathVariable Integer roleId) {
        Role role = roleService.getRoleById(roleId);
        if (role != null) {
            return Result.success("获取角色成功", role);
        }
        return Result.error("404", "角色不存在");
    }
    
    @ApiOperation("获取角色及其权限")
    @GetMapping("/{roleId}/permissions")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Role> getRoleWithPermissions(@PathVariable Integer roleId) {
        Role role = roleService.getRoleWithPermissions(roleId);
        if (role != null) {
            return Result.success("获取角色权限成功", role);
        }
        return Result.error("404", "角色不存在");
    }
    
    @ApiOperation("创建角色")
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Role> createRole(@RequestBody RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        Role createdRole = roleService.createRole(role);
        
        // 如果有权限ID列表，则分配权限
        if (roleDTO.getPermissionIds() != null && !roleDTO.getPermissionIds().isEmpty()) {
            roleService.updateRolePermissions(createdRole.getRoleId(), roleDTO.getPermissionIds());
        }
        
        return Result.success("创建角色成功", createdRole);
    }
    
    @ApiOperation("更新角色")
    @PutMapping("/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Role> updateRole(@PathVariable Integer roleId, @RequestBody RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        role.setRoleId(roleId);
        Role updatedRole = roleService.updateRole(role);
        
        // 更新角色权限
        if (roleDTO.getPermissionIds() != null) {
            roleService.updateRolePermissions(roleId, roleDTO.getPermissionIds());
        }
        
        if (updatedRole != null) {
            return Result.success("更新角色成功", updatedRole);
        }
        return Result.error("500", "更新角色失败");
    }
    
    @ApiOperation("删除角色")
    @DeleteMapping("/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> deleteRole(@PathVariable Integer roleId) {
        boolean deleted = roleService.deleteRole(roleId);
        if (deleted) {
            return Result.success("删除角色成功", true);
        }
        return Result.error("500", "删除角色失败");
    }
    
    @ApiOperation("为角色分配权限")
    @PostMapping("/{roleId}/permissions/{permissionId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> assignPermissionToRole(@PathVariable Integer roleId, @PathVariable Integer permissionId) {
        boolean assigned = roleService.assignPermissionToRole(roleId, permissionId);
        if (assigned) {
            return Result.success("分配权限成功", true);
        }
        return Result.error("500", "分配权限失败");
    }
    
    @ApiOperation("从角色移除权限")
    @DeleteMapping("/{roleId}/permissions/{permissionId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> removePermissionFromRole(@PathVariable Integer roleId, @PathVariable Integer permissionId) {
        boolean removed = roleService.removePermissionFromRole(roleId, permissionId);
        if (removed) {
            return Result.success("移除权限成功", true);
        }
        return Result.error("500", "移除权限失败");
    }
    
    @ApiOperation("更新角色权限")
    @PutMapping("/{roleId}/permissions")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> updateRolePermissions(@PathVariable Integer roleId, @RequestBody List<Integer> permissionIds) {
        boolean updated = roleService.updateRolePermissions(roleId, permissionIds);
        if (updated) {
            return Result.success("更新角色权限成功", true);
        }
        return Result.error("500", "更新角色权限失败");
    }
    
    /**
     * 检查用户是否为管理员
     */
    private boolean hasAdminRole(Integer userId) {
        User user = userMapper.selectById(userId);
        return user != null && "admin".equalsIgnoreCase(user.getRole());
    }
} 